<template>
  <div class="work-orders page-container">
    <div class="page-header">
      <h2>工单管理</h2>
      <el-button type="primary" :icon="Plus" @click="$router.push('/work-orders/create')">
        创建工单
      </el-button>
    </div>

    <el-card>
      <div class="filter-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchQuery"
              placeholder="搜索工单..."
              :prefix-icon="Search"
              clearable
            />
          </el-col>
          <el-col :span="4">
            <el-select v-model="statusFilter" placeholder="状态筛选" clearable>
              <el-option label="全部" value="" />
                            <el-option label="未分配" value="未分配" />
              <el-option label="待处理" value="pending" />
              <el-option label="处理中" value="processing" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="loadWorkOrders">搜索</el-button>
          </el-col>
          <el-col :span="6" v-if="canShowAll">
            <el-switch
              v-model="showAll"
              active-text="显示所有工单"
              @change="loadWorkOrders"
            />
          </el-col>
        </el-row>
      </div>

      <el-table :data="workOrders" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="工单号" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)">
              {{ getPriorityText(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assignee" label="负责人" width="120" />
        <el-table-column prop="area_name" label="区域" width="120" />
        <el-table-column prop="created_at" label="创建时间" width="150" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row.id)">查看</el-button>
            <el-button size="small" type="primary" @click="editWorkOrder(scope.row.id)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteWorkOrder(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/auth'



const userStore = useUserStore()
const router = useRouter()

const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('pending')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const showAll = ref(false)

const canShowAll = computed(() => {
  return ['admin', 'superuser'].includes(userStore.user?.role || '')
})

const workOrders = ref([])

const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    pending: 'warning',
    assigned: 'info',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    pending: '待处理',
    assigned: '已分配',
    in_progress: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

const getPriorityType = (priority: string) => {
  const types: Record<string, string> = {
    low: 'info',
    medium: 'warning',
    high: 'danger'
  }
  return types[priority] || 'info'
}

const getPriorityText = (priority: string) => {
  const texts: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return texts[priority] || priority
}

import api from '@/api'

const loadWorkOrders = async () => {
  loading.value = true
  try {
    const params: any = {
      page: currentPage.value,
      per_page: pageSize.value,
      search: searchQuery.value,
      status: statusFilter.value
    }

    if (canShowAll.value && showAll.value) {
      params.show_all = true
    }

    const response = await api.getWorkOrders(params)
    workOrders.value = response.work_orders
    total.value = response.total
  } catch (error) {
    console.error('加载工单失败:', error)
    ElMessage.error('加载工单失败')
  } finally {
    loading.value = false
  }
}



const viewDetail = (id: string) => {
  router.push(`/work-orders/${id}`)
}

const editWorkOrder = (id: string) => {
  router.push(`/work-orders/${id}/edit`)
}

const deleteWorkOrder = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个工单吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await api.deleteWorkOrder(id)
    
    ElMessage.success('删除成功')
    loadWorkOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadWorkOrders()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadWorkOrders()
}

onMounted(() => {
  loadWorkOrders()
})
</script>

<style scoped>
.work-orders {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.filter-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>